//
// Generated from archetype; please customize.
//

package org.cirrostratus

import groovy.util.GroovyTestCase

/**
 * Tests for the {@link Example} class.
 */
class Ec2LightTest extends GroovyTestCase {
    def getEc2Instance() {
        new Ec2Light('X','X')
    }
    
   def testCreateOptionalParams() {
        def ec2 = getEc2Instance()
        
        def args=['i-12345678']
        def ret = ec2.createOptionalParams(args, ec2.methodMap.din)
        
        assertEquals  'i-12345678', ret['InstanceId.1']
    }

    def testCreateOptionalParamsSmartWay() {
        def ec2 = getEc2Instance()
        
        def args= [new Expando('instanceId':'i-12345678')]
        def ret = ec2.createOptionalParams(args, ec2.methodMap.din)
        
        assertEquals  'i-12345678', ret['InstanceId.1']
    }
    
    void testSmartDefaultArgument() {
        def instance = fakeEc2xml(dinXml){ec2-> ec2.din('i-12345678')}
        def ret = fakeEc2xml(dinXml){ec2-> ec2.din(instance)}
        
        assertEquals 'i-884ef0e0', ret.instanceId
    }

    void testWaitForInstanceStateSucceed() {
        def ec2 = getEc2Instance()
        ec2.warning=false
        
        def counter=0
        ec2.metaClass.din={
            counter++;
            if (counter < 3) {
                return new Expando(instanceState:'pending')
            } else {
                return new Expando(instanceState:'running')
            }
        }
        
        ec2.waitForInstanceState('i-12345678', 'running', 10,0)
        assertEquals 3,counter
    }

    void testWaitForInstanceStateSucceedSmartArg() {
        def instance = fakeEc2xml(dinXml){ec2Light-> ec2Light.din('i-12345678')}

        def ec2 = getEc2Instance()
        ec2.warning=false
        
        def counter=0
        ec2.metaClass.din={
            counter++;
            if (counter < 3) {
                return new Expando(instanceState:'pending')
            } else {
                return new Expando(instanceState:'running')
            }
        }
        
        ec2.waitForInstanceState(instance, 'running', 10,0)
        assertEquals 3,counter
    }
    
    void testWaitForInstanceStateFails() {
        def ec2 = getEc2Instance()
        ec2.warning=false
        
        def counter=0
        ec2.metaClass.din={
            counter++;
            return new Expando(instanceState:'pending')
        }
        
        shouldFail(Exception.class){
            ec2.waitForInstanceState('i-12345678', 'running', 1,1)
        }
        
        assertEquals 2,counter
    }
    
    void testDetachVolumeParser() {
        def resp = fakeEc2xml(detvolXml){ec2-> ec2.detvol()}
        assertEquals 'vol-4d826724', resp.volumeId
        assertEquals 'detaching', resp.status
        assertEquals '/dev/sdh', resp.device
        
    }
    
    void testDeleteVolumeParser() {
        def resp = fakeEc2xml(delvolXml){ec2-> ec2.delvol()}
        assertEquals 'true', resp.return
    }
    
    void testCreateVolumeParser() {
        def resp = fakeEc2xml(addvolXml){ec2-> ec2.addvol()}
        assertEquals 'vol-4d826724', resp.volumeId
        assertEquals '800', resp.size
    }

    void testDescribeAddressesParser() {
        def resp = fakeEc2xml(daddrXml){ec2-> ec2.daddr()}
        assertEquals 2, resp.size()
        assertEquals 'i-f15ebb98', resp[0].instanceId
        assertEquals '67.202.55.255', resp[0].publicIp
        assertEquals null, resp[1].instanceId
        
    }

    void testDescribeSnapshotsParser() {
        def resp = fakeEc2xml(dsnapXml){ec2-> ec2.dsnap()}
        
        assertEquals 'snap-78a54011', resp.snapshotId
        assertEquals '10', resp.volumeSize
    }

    void testDescribeVolumesParser() {
        def resp = fakeEc2xml(dvolXml){ec2-> ec2.dvol()}
        assertEquals 'vol-4282672b', resp.volumeId
        assertEquals 'i-6058a509:/dev/sdh', resp.attachmentSet
    }

    void testDescribeInstancesParser() {
        def resp = fakeEc2xml(dinXml){ec2-> ec2.din()}
        assertEquals 'i-884ef0e0', resp.instanceId
    }
    
    void testCreateExpandoFromNode() {
        def ec2 = getEc2Instance()
        def rootNode = new XmlParser().parseText(instanceItem)
        
        def expando = ec2.createExpandoFromNode(rootNode,null)
        
        assertEquals 'i-884ef0e0', expando.instanceId
        assertEquals 'ami-85be58ec', expando.imageId
        assertEquals 'disabled', expando.monitoring
        assertEquals 'us-east-1a', expando.placement
        assertEquals 'running', expando.instanceState
        assertEquals '174.129.227.38', expando.ipAddress
    }

    def fakeEc2xml(xml, closure) {
        def connectionMock = new groovy.mock.interceptor.StubFor(sun.net.www.protocol.https.HttpsURLConnectionImpl)        
        connectionMock.demand.getInputStream{new Expando(text:xml)}

        def ec2 = getEc2Instance()
        //ec2.debug=true
        ec2.trace=false
        def resp
        connectionMock.use{
            resp = closure(ec2)
        }
        return resp
    }
    
    static detvolXml='''
    <DetachVolumeResponse xmlns="http://ec2.amazonaws.com/doc/2009-08-15/">
      <volumeId>vol-4d826724</volumeId>
      <instanceId>i-6058a509</instanceId>
      <device>/dev/sdh</device>
      <status>detaching</status>
      <attachTime>2008-05-08T11:51:50.000Z</attachTime>
    </DetachVolumeResponse>
    '''

    static xxxXml='''
    '''
    
    static delvolXml='''
    <DeleteVolumeResponse xmlns="http://ec2.amazonaws.com/doc/2009-08-15/">
      <return>true</return>
    </DeleteVolumeResponse>
    '''
    
    static addvolXml='''<CreateVolumeResponse xmlns="http://ec2.amazonaws.com/doc/2009-08-15/">
      <volumeId>vol-4d826724</volumeId>
      <size>800</size>
      <status>creating</status>
      <createTime>2008-05-07T11:51:50.000Z</createTime>
      <availabilityZone>us-east-1a</availabilityZone>
      <snapshotId></snapshotId>
    </CreateVolumeResponse>
    '''
    
    static daddrXml='''
    <DescribeAddressesResponse xmlns="http://ec2.amazonaws.com/doc/2009-08-15/">
      <addressesSet>
        <item>
          <instanceId>i-f15ebb98</instanceId>
          <publicIp>67.202.55.255</publicIp>
        </item>
        <item>
          <publicIp>67.202.55.233</publicIp>
        </item>
      </addressesSet>
    </DescribeAddressesResponse>
    '''
    
    static dsnapXml='''<DescribeSnapshotsResponse xmlns="http://ec2.amazonaws.com/doc/2009-08-15/">
      <snapshotSet>
        <item>
          <snapshotId>snap-78a54011</snapshotId>
          <volumeId>vol-4d826724</volumeId>
          <status>pending</status>
          <startTime>2008-05-07T12:51:50.000Z</startTime>
          <progress>80%</progress>
          <ownerId>218213537122</ownerId>
          <volumeSize>10</volumeSize>
          <description>Daily Backup</description>
        </item>
      </snapshotSet>
    </DescribeSnapshotsResponse>
    '''
    static dvolXml='''<DescribeVolumesResponse xmlns="http://ec2.amazonaws.com/doc/2009-08-15/">
    <volumeSet>
      <item>
        <volumeId>vol-4282672b</volumeId>
        <size>800</size>
        <snapshotId/>
        <availabilityZone>us-east-1a</availabilityZone>
        <status>in-use</status>
        <createTime>2008-05-07T11:51:50.000Z</createTime>
        <attachmentSet>
          <item>
            <volumeId>vol-4282672b</volumeId>
            <instanceId>i-6058a509</instanceId>
            <device>/dev/sdh</device>
            <status>attached</status>
            <attachTime>2008-05-07T12:51:50.000Z</attachTime>
          </item>
        </attachmentSet>
      </item>
    </volumeSet>
    </DescribeVolumesResponse>
    '''
    static dinXml = """
    <DescribeInstancesResponse xmlns="http://ec2.amazonaws.com/doc/2009-08-15/">
      <reservationSet>
        <item>
          <reservationId>r-44a5402d</reservationId>
          <ownerId>UYY3TLBUXIEON5NQVUUX6OMPWBZIQNFM</ownerId>
          <groupSet>
            <item>
              <groupId>default</groupId>
            </item>
          </groupSet>
          <instancesSet>
          $instanceItem
          </instancesSet>
              </item>
            </reservationSet>
          </DescribeInstancesResponse>
    """
    
    static instanceItem='''
        <item  xmlns="http://ec2.amazonaws.com/doc/2009-08-15/">
        <instanceId>i-884ef0e0</instanceId>
        <imageId>ami-85be58ec</imageId>
        <instanceState>
            <code>16</code>
            <name>running</name>
        </instanceState>
        <privateDnsName>ip-10-251-90-162.ec2.internal</privateDnsName>
        <dnsName>ec2-174-129-227-38.compute-1.amazonaws.com</dnsName>
        <reason/>
        <keyName>zepp-stairway</keyName>
        <amiLaunchIndex>1</amiLaunchIndex>
        <productCodes>
            <item>
                <productCode>8821D81E</productCode>
            </item>
        </productCodes>
        <instanceType>m1.small</instanceType>
        <launchTime>2009-10-21T10:25:25.000Z</launchTime>
        <placement>
            <availabilityZone>us-east-1a</availabilityZone>
        </placement>
        <kernelId>aki-a71cf9ce</kernelId>
        <ramdiskId>ari-a51cf9cc</ramdiskId>
        <monitoring>
            <state>disabled</state>
        </monitoring>
        <privateIpAddress>10.251.90.162</privateIpAddress>
        <ipAddress>174.129.227.38</ipAddress>
    </item>
    '''

}
